import { toPascalCase } from '@/utils';
import config from '@/config';

// 递归获取 views 文件夹下的所有index.vue文件
const files = import.meta.glob(['@/views/**/index.vue'], {
  eager: true,
  import: 'default'
});

// 免处理白名单
const whiteList = config.route.noAutoList;

// 模块map
// const modules = import.meta.glob(['@/views/**/index.vue']);
const moduleMap: any = {};
// Object.entries(modules).forEach(([path, fn]) => {
//   const key = path.replace(/(\/src\/views\/|\.vue)/g, '');
//   const first = key.split('/')[0];
//   if (!whiteList.includes(first)) {
//     moduleMap[key] = fn;
//   }
// });

// 获得path数组
const pathArr = Object.entries(files)
  // 去除匹配到的开头的/src/views/和结尾的.vue字符串
  .map(([path, config]) => [path.replace(/(\/src\/views\/|\.vue)/g, ''), config])
  // 白名单内的目录无需处理
  .filter(([path, config]) => {
    const first = (path as any).split('/')[0];
    if (!whiteList.includes(first)) {
      moduleMap[path as any] = config;
      return true;
    }
  })
  .map(([path, config]) => path);

// 建立第一级路由数据
const pageMap: any = {};
pathArr.forEach((str) => {
  const arr = (str as any).split('/');
  const first = arr[0];
  if (!Object.hasOwnProperty.call(pageMap, first)) {
    pageMap[first] = { name: first, fullName: first, origin: [] };
  }
  pageMap[first].origin.push({ path: arr.slice(1) });
});

// 补全深层路由数据
generateRouteData(pageMap);
// 生成children数组
const obj = { pageMap: pageMap };
generateChildren(obj);

const modules = Object.entries(pageMap).map(([path, config]) => config);
generateRoute(modules);

// 补全深层路由数据
function generateRouteData(obj: any) {
  Object.keys(obj).forEach((key) => {
    obj[key].pageMap = {};
    obj[key].origin.forEach((item: any) => {
      const arr = item.path;
      if (arr.length) {
        const first = arr[0];
        if (!Object.hasOwnProperty.call(obj[key].pageMap, first)) {
          obj[key].pageMap[first] = { name: first, fullName: obj[key].fullName + '/' + first, origin: [] };
        }
        obj[key].pageMap[first].origin.push({ path: arr.slice(1) });

        if (arr.slice(1).length >= 1) {
          generateRouteData(obj[key].pageMap);
        }
      }
    });
  });
}

// 生成children数组
function generateChildren(obj: any) {
  Object.entries(obj.pageMap).map(([key, value]) => {
    obj.children = obj.children || [];
    obj.children.push(value);
    if (Object.hasOwnProperty.call(value, 'pageMap') && JSON.stringify((value as any).pageMap) !== '{}') {
      generateChildren(value);
    }
  });
}

// 生成路由规则
function generateRoute(routeData: any[], parent: any = {}) {
  routeData.forEach((config) => {
    config.path = config.name;
    delete config.pageMap;
    delete config.origin;
    if (config.name !== 'index') {
      const nameArr = config.fullName.replaceAll('-', '/').split('/');
      const strArr = nameArr.map((name: any) => toPascalCase(name));
      config.name = strArr.join('');
      config.redirect = { name: strArr.join('') + 'Index', fullName: config.fullName + '/index' };
      generateRoute(config.children, config);
    } else {
      config.children = [];
      config.component = moduleMap[config.fullName];
      config.name = config.component.name;
      config.meta = config.component.meta;
      if (JSON.stringify(parent) !== '{}') {
        // 当parent有值，表示倒数第二层路由的meta值由其子提供
        parent.meta = config.component.meta.parent;
        // 处理一级菜单的情况
        if (!parent.meta) {
          parent.meta = config.component.meta;
          parent.component = config.component;
          parent.children = [];
          delete parent.redirect;
        }
      }
    }
  });
}

export default modules;
